package cn.kgc.controller;

import cn.kgc.common.constant.Constants;
import cn.kgc.pojo.SmbmsRole;
import cn.kgc.pojo.SmbmsUser;
import cn.kgc.service.RoleService;
import cn.kgc.service.UserService;
import cn.kgc.utils.PageInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("user")
public class UserController {
    private  Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private UserService service;

    @Resource
    private RoleService rservice;

    @RequestMapping({"/","/toLogin"})
    public String toLogin(){
        return "login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@RequestParam("userCode")String userCode,
                        @RequestParam("userPassword")String userPassword,
                        HttpServletRequest request,
                        Model model){
        logger.info("userCode=="+userCode+"userPassword=="+userPassword);
        SmbmsUser smbmsUser = service.getdenglu(userCode,userPassword);
        if (smbmsUser != null){
            HttpSession session = request.getSession();
            session.setAttribute(Constants.USER_SESSION,smbmsUser);
            return "redirect:/user/tossm";
        }else {
            model.addAttribute("error","用户名或者密码错误");
            return "login";
        }
    }
    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return "redirect:/user/";
    }

    @RequestMapping("/limit")
    public String limit(@RequestParam(value = "currentPageNo",required = false) Integer currentPageNo,
                        @RequestParam(value = "pageSize",required = false) Integer pageSize,
                        @RequestParam(value = "userRole",required = false) Integer userRole,
                        @RequestParam(value = "userName",required = false) String userName,
                        Model model){
        PageInfo pageInfo = new PageInfo();
        if (currentPageNo != null){
            pageInfo.setCurrentPageNo(currentPageNo);
        }
        if (pageSize!=null){
            pageInfo.setPageSize(pageSize);
        }
        int totalConut = service.getConut(userName,userRole);
        pageInfo.setTotalConut(totalConut);
        List<SmbmsUser> list = service.getByPage(userName,userRole,pageInfo.getCurrentPageNo(),pageInfo.getPageSize());
        pageInfo.setData(list);
        List<SmbmsRole> list1 = rservice.getRole();
        model.addAttribute("role",list1);
        model.addAttribute("page",pageInfo);
        model.addAttribute("userName",userName);
        model.addAttribute("userRole",userRole);
        return "index2";
    }


    @RequestMapping("/toAdd")
    public String toAdd(){
        return "userAdd";
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(SmbmsUser smbmsUser,
                      HttpServletRequest request,
                      @RequestParam(value = "files",required = false)MultipartFile[] files){
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        logger.info(path);
        for(int i = 0;i < files.length ;i++){
            MultipartFile attach = files[i];
            if(!attach.isEmpty()){
                if(i == 0){
                    errorInfo = "uploadFileError";
                }else if(i == 1){
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("uploadFile oldFileName ============== > "+oldFileName);
                String prefix= FilenameUtils.getExtension(oldFileName);//原文件后缀
                logger.debug("uploadFile prefix============> " + prefix);
                int filesize = 500000;
                logger.debug("uploadFile size============> " + attach.getSize());
                if(attach.getSize() >  filesize){//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                    String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if(i == 0){
                        idPicPath = path+File.separator+fileName;
                    }else if(i == 1){
                        workPicPath = path+File.separator+fileName;
                    }
                    logger.debug("idPicPath: " + idPicPath);
                    logger.debug("workPicPath: " + workPicPath);

                }else{
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if(flag){
            HttpSession session = request.getSession();
            SmbmsUser smbmsUser1 = (SmbmsUser) session.getAttribute(Constants.USER_SESSION);
            smbmsUser.setCreatedBy(smbmsUser1.getId());
            smbmsUser.setCreationDate(new Date());
            logger.info("====idPicPath=="+idPicPath);
            smbmsUser.setIdPicPath(idPicPath);
            smbmsUser.setWorkPicPath(workPicPath);
            if(service.addUser(smbmsUser)){
                //使用重定向
                return "redirect:/user/limit";
            }else {
                return "userAdd";
            }
        }
        flag = service.addUser(smbmsUser);
        if (flag){
            return "redirect:/user/limit";
        }else {
            return "userAdd";
        }
    }

    @RequestMapping("/downLoad")
    public void downLoad(@RequestParam("id") Integer id,
                           HttpServletResponse response){
        logger.info("idPicPath==============="+id);
        String fileName = service.getId(id).getIdPicPath();

        try {
            InputStream is = new FileInputStream(new File(fileName));

            String filename = "下载文件.jpg";
            filename = URLEncoder.encode(filename,"UTF-8");

            response.addHeader("Content-Dispostion","attachment;filename="+filename);
            response.setContentType("multipart/form-data");
            BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            while ((len = is.read()) != -1){
                os.write(len);
                os.flush();
            }
            os.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam("id")Integer id,Model model){
        SmbmsUser smbmsUser = service.getId(id);
        model.addAttribute("user",smbmsUser);
        return "userUpdate";
    }
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String update(SmbmsUser smbmsUser){

        boolean flag = service.updateUser(smbmsUser);
        if (flag){
            return "redirect:/user/limit";
        }else {
            return "userUpdate";
        }
    }


    @RequestMapping("/toView")
    public String toView(@RequestParam("id")Integer id,Model model){
        SmbmsUser smbmsUser = service.getId(id);
        model.addAttribute("user",smbmsUser);
        return "userView";
    }

        @RequestMapping("/toDel")
    public String toDel(@RequestParam("id")Integer id){
        boolean flag = service.delId(id);
        if (flag){
            return "redirect:/user/limit";
        }
        return "index2";
    }

//    @ExceptionHandler(value={RuntimeException.class})
//    public String handlerException(RuntimeException e,Model model){
//        model.addAttribute("e", e);
//        return "/error/error";
//    }


    @RequestMapping("/userIsExist/{userCode}")
    @ResponseBody
    public JSONObject  userIsExist(@PathVariable String userCode){

        logger.info("userCode======="+userCode);
        SmbmsUser smbmsUser = service.getUserCode(userCode);
        JSONObject jsonObject = new JSONObject();
        if (smbmsUser == null){
            jsonObject.put("code","10000");
            jsonObject.put("msg","可以使用");
        }else {
            jsonObject.put("code","10001");
            jsonObject.put("msg","不可以使用");
        }
        return jsonObject;
    }


    @RequestMapping("/getId/{id}")
    @ResponseBody
    public SmbmsUser getId(@PathVariable Integer id){
        SmbmsUser smbmsUser = service.getId(id);
        return smbmsUser;
    }

    @RequestMapping("/tossm")
    public String asd(){
        return "asd";
    }
}
